import {messageStore} from "@/stores/modules/messageStore.js";
import {message} from 'ant-design-vue'
import {getCompanyInfoById, getJobInfoById} from "@/api/company.js";
import {getStuInfo, getStuInfoByStuId} from "@/api/stu.js";
import {getAllMessage} from "@/api/message.js";

// 更新消息方法
export const updateMessage = async () => {
    try {
        const res = await getAllMessage();
        if (res.data.code === 200) {
            const chatSessions = res.data.data.chatSessions;

            //获取当前用户
            const currentUser = res.data.data.nowRole
            messageStore().setNowRole(currentUser)

            // 为每个chatSession获取公司和职位信息，并更新到store中
            const updatedChatSessions = await Promise.all(
                chatSessions.map(async (session) => {
                    const companyInfo = await getCompanyInfo(session.companyId);  // 调用工具类方法
                    const jobInfo = await getJobInfo(session.jobId);              // 调用工具类方法
                    const stuInfo = await getStudentInfo(session.studentId)

                    // 将公司和职位信息加到session中
                    return {
                        ...session,
                        companyInfo,
                        jobInfo,
                        stuInfo
                    };
                })
            );

            // 更新messageStore
            messageStore().setMessageInfo(updatedChatSessions);
        } else {
            throw new Error(res.data.message);
        }
    } catch (error) {
        message.error('获取消息列表失败');
    }
};

export const getCompanyInfo = async (companyId) => {
    try {
        const res = await getCompanyInfoById({ companyId });
        if (res.data.code === 200) {
            return res.data.data; // 返回公司信息
        } else {
            throw new Error(res.data.message)
        }
    } catch (error) {
        message.error('获取公司信息失败');
    }
};

export const getStudentInfo = async (studentId)=>{
    try{
        const res = await getStuInfoByStuId({
            studentId: studentId
        })
        if(res.data.code === 200){
            return res.data.data
        }else {
            throw new Error(res.data.message)
        }
    }catch{
        message.error('获取学生信息失败')
    }
}

export const getJobInfo = async (jobId)=>{
    try{
        const res = await getJobInfoById({
            jobId: jobId
        })
        if(res.data.code === 200){
            return res.data.data
        }else {
            throw new Error(res.data.message)
        }
    }catch{
        message.error('获取岗位信息失败')
    }
}
